/*
 * @Description:
 * @Autor: fage
 * @Date: 2022-06-06 13:52:09
 * @LastEditors: lanmeng656 cbf0311@sina.com
 * @LastEditTime: 2022-11-18 10:45:56
 */
const express = require("express");
const compression = require("compression");
const path = require("path");
const favicon = require("serve-favicon");
const logger = require("morgan");
const moment = require("moment");
const cookieParser = require("cookie-parser");
const sessionHelper = require("./utils/session-helper");
const bodyParser = require("body-parser");
const gitee = require("./webhooks/gitee");
const gogs = require("./webhooks/gogs");
const common = require("./utils/common.js");
const login = require("./controls/login");
const manage = require("./controls/manage");
var expressWs = require("express-ws");
global.wsClients = [];

//config the http server port
const port = 453;

const app = express();
expressWs(app);
var router = express.Router();
app.use(compression()); //gzip
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false, limit: "10000kb" }));
app.use(favicon(path.join(__dirname, "public", "favicon.ico")));
logger.token("time", function (req, res) {
  return moment().format("YYYY-MM-DD HH:mm:ss");
});
logger.token("realip", function (req, res) {
  if (!req || !req.ip) return "";
  return req.ip.replace("::ffff:", "");
});
logger.token("host", function (req, res) {
  return req.headers.host;
});
app.use(
  logger(":time :method :status :host :realip :url", {
    skip: function (req, res) {
      return res.statusCode == 200 || res.statusCode == 304;
    },
  })
);
app.use(cookieParser());
app.use(sessionHelper());
app.use(express.static(path.join(__dirname, "public")));

router.post("/webhook/gitee", gitee);
router.post("/webhook/gogs", gogs);
router.post("/api/login", login);
router.post("/api/manage", manage);
app.use(router);
app.use(express.static(path.join(__dirname, "public")));
app.ws("/ws", function (ws, req) {
  global.wsClients.push(ws);
  console.log("new ws client,now client count:", global.wsClients.length);
  ws.on("message", function (msg) {
    console.log(msg);
  });
  ws.on("close", function (msg) {
    let index = global.wsClients.indexOf(ws);
    if (index > -1) {
      global.wsClients.splice(index, 1);
    }
    console.log("ws client close,now client count:", global.wsClients.length);
  });
});

app.use(function (req, res, next) {
  console.log("404", req.url);
  res.send("404");
});

app.listen(port);
console.log(common.timestr(), "listing on", port);
